﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Runtime.Serialization.Json;
using System.IO;

namespace TempDataInterfaceDLL
{
    public partial class TempDataInterface
    {
        public Thread[] GetDataThreadIns;
        bool[] isGetData;
        private void PeriodGetDataProc()
        {
            try
            {
                while (!bPeriodGetDataThreadStop)
                {
                    count++;
                    //                 if (count >10000 )
                    //                 {
                    //                     for (int i = 0; i < 30; i++)
                    //                     {
                    //                         WebResponse[i] = new WFHttpWebResponse();
                    //                     }
                    //                 }
                    ShowTextLogProc("-----------------------------第" + count.ToString() + "次访问--------------------------"+SoftVer, 0);
                    FirstIntCheckTime = DateTime.Now;
                    for (int i = 0; i < maxGetdataThread; i++)
                    {
                        GetDataThreadIns[i] = new Thread(new ParameterizedThreadStart(GetDataProc));
                        GetDataThreadIns[i].Name = (i + 1).ToString() + "线程获取数据";
                        ShowTextLogProc((i + 1).ToString() + "线程获取数据", 0);
                        GetDataThreadIns[i].Start(i + 1);
                        isGetData[i] = true;
                    }


                    //                     int i = 1;
                    //                     GetDataThreadIns[i] = new Thread(new ParameterizedThreadStart(GetDataProc));
                    //                     GetDataThreadIns[i].Name = (i + 1).ToString() + "线程获取数据";
                    //                     ShowTextLogProc((i + 1).ToString() + "线程获取数据");
                    //                     GetDataThreadIns[i].Start(i + 1);
                    //                     isGetData[i] = true;


                    bool bfinish = false;
                    while (!bfinish)
                    {
                        bfinish = true;
                        for (int j = 0; j < maxGetdataThread; j++)
                        {
                            if (isGetData[j])
                                bfinish = false;
                        }
                    }
                    CheckData();
                    Thread.Sleep(10000);
                }
                bPeriodGetDataThreadIsStop = true;
            }
            catch (System.Exception ex)
            {
                ShowTextLogProc("重要错误" + ex.Message, 0);
            }
        }
        private void GetDataProc(object index)
        {
            int n = (int)index;
            n--;
            Thread.Sleep(n * 1000);
            int count = 30 / maxGetdataThread;
            int start = n * count;
            for (int i = start; i < (start + count); i++)
            {
                pageIndex[i] = 1;
                GetDatas[i] = null;
            }
            bool bfinish = false;
            DateTime dt1, dt2;
            while (!bfinish)
            {
                bfinish = true;
                dt1 = DateTime.Now;
                for (int i = start; i < (start + count); i++)
                {
                    if (pageIndex[i] != int.MinValue)//未采集完成
                    {
                        GetData(i, pageIndex[i]);
                        if (pageIndex[i] != int.MinValue)
                            bfinish = false;
                    }
                }
                if (bfinish)
                    break;
                while (true)
                {
                    dt2 = DateTime.Now;
                    if (dt2 > dt1.AddSeconds(10))
                        break;
                    Thread.Sleep(50);
                }
            }
            for (int i = start; i < (start + count); i++)
            {
                if (GetDatas[i] != null)
                {
                    DateTime dt = GetDatas[i][0].callin_time;
                    for (int j = 0; j < GetDatas[i].Count; j++)
                    {
                        if (dt < GetDatas[i][j].callin_time)
                        {
                            dt = GetDatas[i][j].callin_time;
                        }
                    }
                    LastGetTime[i] = dt.AddSeconds(1);
                }
            }
            ShowTextLogProc("分组线程" + index.ToString() + "获得数据完毕!", n);
            isGetData[n] = false;
        }
        public void GetData(int index, int curpage)
        {
            int page = 1;
            int retry = 5;
            string url;
            string web = "";
            page = curpage;
            try
            {
                while (retry != 0)
                {
                    retry--;
                    if (retry < 3)
                        Thread.Sleep(10000);
                    url = "http://www.c4006.com/customer/servlet/GetExtensionCallerByID.ts?beginTime=";
                    url += LastGetTime[index].ToString("yyyy-MM-dd HH:mm:ss");//含当前这秒
                    url += "&endTime=";
                    url += FirstIntCheckTime.ToString("yyyy-MM-dd HH:mm:ss");//DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    url += "&page=" + page.ToString();
                    url += "&limit=100";
                    HttpWebResponse hr = WebResponse[index].CreateGetHttpResponse(url);
                    web = WebResponse[index].Content;
                    DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(myData));
                    MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(WebResponse[index].Content));
                    myData calldata = (myData)s.ReadObject(stream);
                    //ShowTextLogProc(url);
                    ShowTextLogProc(LastGetTime[index].ToString("yyyy-MM-dd HH:mm:ss") + "~" + FirstIntCheckTime.ToString("yyyy-MM-dd HH:mm:ss") + ":" + "用户" + index.ToString() + ":" + WebResponse[index].Content, index % CombinationThreadCount);
                    if (!calldata.success)
                    {
                        Login(index);
                        continue;
                    }
                    else
                    {
                        if (calldata.data.Length != 0)
                        {
                            if (GetDatas[index] == null)
                                GetDatas[index] = new List<CallData>();
                            for (int j = 0; j < calldata.data.Length; j++)
                            {
                                CallData d = new CallData();
                                d.UserIndex = index;
                                d.caller = calldata.data[j].caller;
                                try
                                {
                                    d.callin_time = DateTime.Parse(calldata.data[j].callin_time);
                                }
                                catch
                                {
                                    ShowTextLogProc("用户" + index.ToString() + "的数据中存在无效字符串：" + calldata.data[j].callin_time, index % CombinationThreadCount);
                                    continue;
                                }
                                GetDatas[index].Add(d);
                            }
                            if (calldata.count > (calldata.data.Length + (page - 1) * 100))
                            {
                                pageIndex[index]++;
                                int left = calldata.count - (page - 1) * 100;
                                ShowTextLogProc("用户" + index.ToString() + "延时等待，剩余" + left.ToString() + "条数据", index % CombinationThreadCount);
                                break;
                            }
                            else
                            {
                                pageIndex[index] = int.MinValue;//取数完成
                                break;
                            }
                        }
                        else
                        {
                            pageIndex[index] = int.MinValue;//取数完成
                            break;
                        }
                    }
                }
                if (retry == 0)//失败
                {
                    ShowTextLogProc("用户" + index.ToString() + "获得数据失败!", index % CombinationThreadCount);
                }
            }
            catch (System.Exception ex)
            {
                ShowTextLogProc("用户" + index.ToString() + ":" + web + ex.Message, index % CombinationThreadCount);
            }
            //             if (ret != null)
            //             {
            //                 DateTime dt = ret[0].callin_time;
            //                 for (int i = 0; i < ret.Count; i++)
            //                 {
            //                     if (dt < ret[i].callin_time)
            //                     {
            //                         dt = ret[i].callin_time;
            //                     }
            //                 }
            //                 LastGetTime[index] = dt.AddSeconds(1);
            //             }
            //             ShowTextLogProc("用户" + index.ToString() + "数据获得完毕，等待处理!");
            //             return ret;
        }
    }
}
